<template>
  <div class="todo-app">
    <header>
      <h1>TodoList 待办事项</h1>
    </header>

    <main>
      <!-- 任务添加区域 -->
      <div class="todo-input">
        <input 
          v-model="newTodo.title" 
          type="text" 
          placeholder="输入待办事项..." 
          @keyup.enter="addTodo"
          :class="{ 'error': !newTodo.title.trim() }"
        >
        <button @click="addTodo" :disabled="!newTodo.title.trim()">
          添加任务
        </button>
      </div>

      <!-- 统计信息 -->
      <div class="todo-stats" v-if="todos.length > 0">
        <span>
          共 {{ todos.length }} 项任务，已完成 {{ completedTodos.length }} 项
        </span>
        <button @click="clearCompleted">清除已完成</button>
      </div>

      <!-- 任务列表 -->
      <ul class="todo-list" v-if="todos.length > 0">
        <li 
          v-for="todo in filteredTodos" 
          :key="todo.id" 
          class="todo-item"
          :class="{ 'completed': todo.completed }"
        >
          <input 
            type="checkbox" 
            v-model="todo.completed"
            @change="toggleTodoStatus(todo)"
          >
          <span class="todo-text" @dblclick="editTodo(todo)">{{ todo.title }}</span>
          <button @click="removeTodo(todo)" class="delete-btn">删除</button>
        </li>
      </ul>

      <!-- 空状态提示 -->
      <div class="empty-state" v-else>
        <p>暂无待办事项，赶紧添加第一个任务吧！</p>
      </div>

      <!-- 筛选按钮 -->
      <div class="todo-filters">
        <button 
          v-for="filter in filters" 
          :key="filter.value" 
          :class="{ 'active': currentFilter === filter.value }"
          @click="setFilter(filter.value)"
        >
          {{ filter.label }}
        </button>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';

// 待办事项数据类型
type Todo = {
  id: number;
  title: string;
  completed: boolean;
};

// 初始化数据
const newTodo = ref({ title: '', completed: false });
const todos = ref<Todo[]>([]);
const currentFilter = ref('all');

// 计算属性 - 已完成的任务
const completedTodos = computed(() => 
  todos.value.filter(todo => todo.completed)
);

// 计算属性 - 过滤后的任务列表
const filteredTodos = computed(() => {
  if (currentFilter.value === 'all') {
    return todos.value;
  } else if (currentFilter.value === 'active') {
    return todos.value.filter(todo => !todo.completed);
  } else {
    return todos.value.filter(todo => todo.completed);
  }
});

// 筛选选项
const filters = ref([
  { value: 'all', label: '全部' },
  { value: 'active', label: '未完成' },
  { value: 'completed', label: '已完成' }
]);

// 添加任务
function addTodo() {
  const title = newTodo.value.title.trim();
  if (!title) return;

  todos.value.unshift({
    id: Date.now(),
    title,
    completed: false
  });

  newTodo.value.title = '';
}

// 切换任务状态
function toggleTodoStatus(todo: Todo) {
  todo.completed = !todo.completed;
}

// 编辑任务
function editTodo(todo: Todo) {
  const newTitle = prompt('编辑任务:', todo.title);
  if (newTitle !== null && newTitle.trim() !== '') {
    todo.title = newTitle.trim();
  }
}

// 删除任务
function removeTodo(todo: Todo) {
  todos.value = todos.value.filter(t => t !== todo);
}

// 清除已完成任务
function clearCompleted() {
  todos.value = todos.value.filter(todo => !todo.completed);
}

// 设置筛选条件
function setFilter(filter: string) {
  currentFilter.value = filter;
}

// 生命周期钩子 - 组件挂载时加载数据（模拟从本地存储加载）
onMounted(() => {
  const savedTodos = localStorage.getItem('todos');
  if (savedTodos) {
    todos.value = JSON.parse(savedTodos);
  }
});

// 生命周期钩子 - 组件卸载前保存数据到本地存储
onBeforeUnmount(() => {
  localStorage.setItem('todos', JSON.stringify(todos.value));
});
</script>

<style scoped>
.todo-app {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Arial', sans-serif;
}

header {
  text-align: center;
  margin-bottom: 30px;
}

h1 {
  color: #333;
  margin: 0;
}

.todo-input {
  display: flex;
  margin-bottom: 20px;
}

.todo-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  font-size: 16px;
}

.todo-input input.error {
  border-color: #f44336;
}

.todo-input button {
  padding: 0 20px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  font-size: 16px;
}

.todo-input button:disabled {
  background-color: #8bc34a;
  cursor: not-allowed;
}

.todo-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 14px;
  color: #666;
}

.todo-stats button {
  background: none;
  border: none;
  color: #4285f4;
  cursor: pointer;
  padding: 0;
}

.todo-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.todo-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.todo-item:last-child {
  border-bottom: none;
}

.todo-item input[type="checkbox"] {
  margin-right: 10px;
  cursor: pointer;
}

.todo-text {
  flex: 1;
  font-size: 16px;
  word-break: break-all;
  cursor: pointer;
  transition: all 0.2s;
}

.todo-item.completed .todo-text {
  text-decoration: line-through;
  color: #999;
}

.todo-item.completed .todo-text:hover {
  color: #666;
}

.delete-btn {
  background: none;
  border: none;
  color: #f44336;
  cursor: pointer;
  padding: 0 5px;
  display: none;
}

.todo-item:hover .delete-btn {
  display: block;
}

.empty-state {
  text-align: center;
  padding: 20px;
  color: #999;
  font-style: italic;
}

.todo-filters {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.todo-filters button {
  background: none;
  border: 1px solid #ddd;
  padding: 5px 10px;
  margin: 0 5px;
  border-radius: 4px;
  cursor: pointer;
  color: #666;
}

.todo-filters button.active {
  background-color: #4285f4;
  color: white;
  border-color: #4285f4;
}
</style>